var countSurgeon = $('tr').filter('#surgeon').length;
var countAnesthesiologist = $('tr').filter('#anesthesiologist').length;
var countNurse = $('tr').filter('#nurse').length;
var startIndex = $('table#surgeryParticipants tr').length;

function isExistent(name,role){
	for(var i=0; i < $("input[id='personNames']").length; i++){
		var objName	=	$("input[id='personNames']").get(i)
		var objRole	=	$("input[id='roles']").get(i);
		if(objName.value==name && objRole.value==role){
			return true;
		}		
	}
	return false;
}
function addParticipant(){
	var row	      = null;
	var name      = '';
	var personId = null;
	
	if ( $('#selectPeople option:selected').val() == '' ) {
		$('#selectPeople option:selected').css("border-color", "red");
 		$('span#statusMessage').text(_('Select Doctor/Technician/Nurse')).show();
 		return;
	}
	
	name = $('#selectPeople option:selected').text();
	personId = $('#selectPeople option:selected').val();
	
	if (name.length == 0) {
		return;
	}
	
	var role      = $('#surgicalRole :selected').val();
	var roleName  = $('#surgicalRole :selected').attr('label');
	if(isExistent(name,role)){
		$('span#statusMessage').text(_('Duplicated Doctor/Technician and Role')).show();
		return;
	}
	$.ajax ({
		type: 	 "POST",
		url:	 "../Surgery/validateEmployeeAjax?set_ajax_view",
		data:	 "name=" + name,
		success: function(data) {
			if (data == 'true') {
				row	=	"<tr id='" + role +"'>"
					+	"<td><span>" + name + "</span><input type='text' name='personNames[]' id='personNames' value='" + personId + "' style='width: 140px; display: none'/></td>"
					+	"<td><span>" + roleName + "</span><input type='text' name='roles[]' id='roles' value='" + role + "' style='width: 140px; display: none'/></td>"
					+	"<td class='action'><a id='p_row_" + startIndex + "' href=\"javascript:removeRole('p_row_" + startIndex + "')\"><img class='imgBtn' src='../images/remove_small.png' border='0' title='" + _("Delete") + "'/></a></td>"
					+	"</tr>";
				$('table#surgeryParticipants').append(row);
			
				switch(role) {
					case '1':
			  			countSurgeon++;
			  			break;
			  		case '2':
			  		    countAnesthesiologist++;
			  		    break;
			  		case '4':
			  			countNurse++;
			  			break;
					default:
			  			break;
				}
				startIndex++;		
				
				$('#personName').val('');
				$('#personName').focus();
				
			} else {
				$('span#statusMessage').text(_("This doctor isn't in the list")).show();
			}
		}
	});
}

function addParticipantFromTemplate(role, roleName, name, personId){
	var row	      = null;
	
	if(isExistent(name,role)){
		$('span#statusMessage').text(_('Duplicated Doctor/Technician and Role')).show();
		return;
	}
	
	row	=	"<tr id='" + role +"'>"
	+	"<td><span>" + name + "</span><input type='text' name='personNames[]' id='personNames' value='" + personId + "' style='width: 140px; display: none'/></td>"
	+	"<td><span>" + roleName + "</span><input type='text' name='roles[]' id='roles' value='" + role + "' style='width: 140px; display: none'/></td>"
	+	"<td class='action'><a id='p_row_" + startIndex + "' href=\"javascript:removeRole('p_row_" + startIndex + "')\"><img class='imgBtn' src='../images/remove_small.png' border='0' title='" + _("Delete") + "'/></a></td>"
	+	"</tr>";
	
	$('table#surgeryParticipants').append(row);
	switch(role) {
		case '1':
				countSurgeon++;
				break;
			case '2':
			    countAnesthesiologist++;
			    break;
			case '4':
				countNurse++;
				break;
		default:
				break;
	}
	startIndex++;		
	
	$('#personName').val('');
	$('#personName').focus();
	
}

function removeRole(id) {
	var thisRole = $('#' + id).parent().parent().attr('id');
	switch(thisRole) {
		case '1':
			countSurgeon--;
			break;    
		case '2':
			countAnesthesiologist--;
			break;
		case '4':
			countNurse--;
			break;
		default:
			break;
	}
	$('#' + id).parent().parent().remove();
}

$(document).ready(function(){
	getUsersByEmployeeType();

	$('input#saveSurgery').bind('click', saveSurgery);		        
    
    $('#surgeryDiagnosis').blur(function() {
    	isNotEmpty($(this), _('Not yet input diagnosis'), 'statusMessage');
    });
    
    $('#eye').blur(function() {
    	isNotEmpty($(this), _('Not yet select surgery eye'), 'statusMessage');
    });
    
    $('input#anesthesia').blur(function() {
    	isNotEmpty($(this), _('Not yet input insensitive method'), 'statusMessage');
    });
    
    $('input#surgicalMethod').blur(function() {
    	isNotEmpty($(this), _('Not yet input surgery method'), 'statusMessage');
    });
       
    $('div#editSurgery').click(function() {
    	$('span#successfulMessage').hide();
    });    
      
});

function saveSurgery() {
	if (isReadyToSubmit()) {
		var submitData = $('#editSurgeryForm').formSerialize();
		$.ajax ({
			type:    "POST",
			url:	 "../Surgery/editSurgeryAjax?set_ajax_view",
			data:	 submitData,
			success: function(data) {
				loadOpenSurgery(data, _("Saving succeed"));
			}
		});
	}
}

function checkParticipant() {
	countSurgeon = 0;
	countAnesthesiologist = 0;
	countNurse = 0;
	var thisRole = $('#surgeryParticipants tbody tr').each(function()
		{
			switch($(this).attr('id')) {
				case '1':
					countSurgeon++;
					break;    
				case '2':
					countAnesthesiologist++;
					break;
				case '4':
					countNurse++;
					break;
				default:
					break;
			}
		}
	);
	
	if (countSurgeon == 0) {
		$('span#statusMessage').text(_('Surgeon is unvailable')).show();
		return false;
	}
	if (countAnesthesiologist == 0) {
		$('span#statusMessage').text(_('Anaesthetist is unvailable')).show();
		return false;
	}
	
	return true;
}

function isReadyToSubmit() {
	if (!checkDate($('input#surgeryDate'), $('input#surgeryDate_mm'), $('input#surgeryDate_dd'), true, _('Empty surgery date'), 'statusMessage', true)) {
		return false;
	}
	

	if ($('#surgeryName').val() == 0) {
		$('#statusMessage').text(_('Surgery name not selected yet'));
		$('#surgeryName').css("border-color", "red");   		
   		return false;
   	} else {
   		$('#surgeryName').css("border-color", "#AAA");    	
    }
 
    if (!isNotEmpty($('#surgeryDiagnosis'), _('Not yet input diagnosis'), 'statusMessage')) {
    	return false;
    }
    
    if (!isNotEmpty($('#anesthesia'), _('Not yet input insensitive method'), 'statusMessage')) {
    	return false;
    }
    
    if (!isNotEmpty($('#surgicalMethod'), _('Not yet input surgery method'), 'statusMessage')) {
    	return false;
    }
    
    if (!checkParticipant()) {
		return false
	}
	
	return true;
}

function uncheck(checkboxId) {
	$('#' + checkboxId).attr('checked', false);

}

function getUsersByEmployeeType(){
	var employee_type_id = $('#surgicalRole option:selected').val();
	$.ajax({
		type:	"GET",
		url:	"../Surgery/GetUserByEmployeeTypeAjax?set_ajax_view",
		data:	"employee_type_id=" + employee_type_id ,
		beforeSend: function() {
			$('#addPartToList').hide();
		},
		complete: function() {
			$('#addPartToList').show();
		},
		success: function(data){
			$('#selectPeople').html('');
			$('#selectPeople').append("<option id='' value=''>-- " + _("Select employee") + " --</option>");
			$('#selectPeople').append(data);
		}
	});
}

function getUsersByEmployeeTypeForTemplate(roleId, employeeId, personId){
	var employee_type_id = $('#' + roleId + ' option:selected').val();
	if (employee_type_id == '') {
		return;
	}
	
	$.ajax({
		type:	"GET",
		url:	"../Surgery/GetUserByEmployeeTypeAjax?set_ajax_view",
		data:	"employee_type_id=" + employee_type_id ,
		success: function(data){
			$('#' + employeeId).html('');
			$('#' + employeeId).append("<option id='' value=''>-- " + _("Select employee") + " --</option>");
			$('#' + employeeId).append(data);
			
			//Select person with personId
			$('#' + employeeId).children().each(function(){
				if ($(this).val() == personId) {
					$(this).attr('selected', 'selected');
					return false;
				}
				
			});
		}
	});
}

function showSurgeryTeamTemplate() {
	$('#surgeryTeamTemplateDialog').dialog('open');
	
}
